/*
 * Copyright (C) 2014 STNet,Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.co.stnet.apps.medcloud.web.api.resources;

import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import jp.co.stnet.apps.medcloud.core.exception.BusinessException;
import jp.co.stnet.apps.medcloud.core.message.ResultMessages;
import jp.co.stnet.apps.medcloud.domain.beans.CommonResponse;
import jp.co.stnet.apps.medcloud.domain.services.api.WithdrawResourceService;
import jp.co.stnet.apps.medcloud.web.common.CreateResult;
import jp.co.stnet.apps.medcloud.web.common.ErrorMessage;

/**
 *
 * @author stnetadmin
 */
@Path("/member/withdraw")
@Service
public class WithdrawResource {

    private static final Logger logger = LoggerFactory.getLogger(WithdrawResource.class);

    /**
     * メッセージ
     */
    @Autowired
    private MessageSource messageSource;

    /**
     * 利用者解除サービス
     */
    @Autowired
    private WithdrawResourceService withdrawResourceService;

    /**
     * クラウド利用者解除
     *
     * @param headers
     * @param username
     * @param password
     * @return
     */
    @DELETE
    @Produces(MediaType.APPLICATION_XML)
    public Response withdraw(
            @Context HttpHeaders headers,
            @FormParam("username") String username,
            @FormParam("password") String password) {

        ResultMessages messages = null;
        CommonResponse commonResponse = new CommonResponse();

        // TODO
        // ヘッダにアクセストークンがあるので username, password は不要。。。
        // 認証ヘッダを取得
        MultivaluedMap httpHeaders = headers.getRequestHeaders();
        String token = (String) httpHeaders.getFirst("authorization");
        String values[] = StringUtils.split(token, " ");

        logger.debug("\n\ttoken type: {}, token={}", values[0], values[1]);
        if (values.length != 2) {
            //return; 401
        }
        if (values[1] != null) {
            token = values[1];
        } else {
            //return; 401
        }

        // クラウド利用者解除処理を行い、応答を返します
        try {
            withdrawResourceService.withdraw(token);
            // 正常系メッセージを生成.
            // エンティティボディがないので応答(response)に結果コード・詳細を載せて返却する
            messages = ResultMessages.success().add("e.md.fw.0204", messageSource);
            commonResponse.setResult(CreateResult.create(messages));
            return Response.status(204).
                    entity(commonResponse).
                    type(MediaType.APPLICATION_XML).
                    build();
        } catch (BusinessException e) {
            // エラー系メッセージを生成
            // エンティティボディがないので応答(response)に結果コード・詳細を載せて返却する
            commonResponse = ErrorMessage.create(e.getResultMessages());
            return Response.status(500).
                    entity(commonResponse).
                    type(MediaType.APPLICATION_XML).
                    build();
        }

    }

}
